<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="时间范围">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="账单状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="待支付" value="待支付" />
            <el-option label="已支付" value="已支付" />
            <el-option label="已过期" value="已过期" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="20" class="mt-20">
      <!-- 统计卡片 -->
      <el-col :span="6">
        <el-card shadow="hover" @click.native="showBillList('total')" class="clickable-card">
          <div class="stat-card">
            <div class="stat-title">总账单数</div>
            <div class="stat-value">{{ summaryData.totalBills }}</div>
            <div class="stat-trend">
              <span :class="summaryData.billTrend >= 0 ? 'up' : 'down'">
                <i :class="summaryData.billTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(summaryData.billTrend) }}%
              </span>
              同比上月
            </div>
          </div>
        </el-card>
      </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">总金额</div>
              <div class="stat-value">¥{{ summaryData.totalAmount }}</div>
              <div class="stat-trend">
              <span :class="summaryData.amountTrend >= 0 ? 'up' : 'down'">
                <i :class="summaryData.amountTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(summaryData.amountTrend) }}%
              </span>
                同比上月
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">已支付</div>
              <div class="stat-value">{{ summaryData.paidBills }}</div>
              <div class="stat-trend">
              <span :class="summaryData.paidTrend >= 0 ? 'up' : 'down'">
                <i :class="summaryData.paidTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(summaryData.paidTrend) }}%
              </span>
                同比上月
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">支付率</div>
              <div class="stat-value">{{ summaryData.paymentRate }}%</div>
              <div class="stat-trend">
              <span :class="summaryData.rateTrend >= 0 ? 'up' : 'down'">
                <i :class="summaryData.rateTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(summaryData.rateTrend) }}%
              </span>
                同比上月
              </div>
            </div>
          </el-card>
        </el-col>
        <!-- 账单列表弹窗 -->
        <el-dialog
            title="账单列表"
            :visible.sync="billListVisible"
            width="80%"
            top="5vh"
            @close="handleDialogClose"
        >
          <el-table
              :data="billList"
              v-loading="listLoading"
              border
              style="width: 100%"
          >
            <el-table-column prop="billId" label="账单ID" width="120" />
            <el-table-column prop="schoolName" label="学校名称" width="180" />
            <el-table-column prop="packageName" label="套餐名称" width="150" />
            <el-table-column prop="amount" label="金额" width="120" align="right">
              <template #default="{row}">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{row}">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="payTime" label="支付时间" width="180" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{row}">
                <el-button size="mini" @click="handleViewDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="listQuery.page"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="listQuery.limit"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </el-dialog>
    </el-row>
      <div class="chart-area">
        <el-row :gutter="20" class="mt-20">
          <!-- 金额趋势图 -->
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>
                <div class="chart-header">
                  <span>月度收入趋势</span>
                  <el-radio-group v-model="amountChartType" size="small">
                    <el-radio-button label="line">折线图</el-radio-button>
                    <el-radio-button label="bar">柱状图</el-radio-button>
                  </el-radio-group>
                </div>
              </template>
              <div class="chart-container">
                <div ref="amountChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>

          <!-- 账单状态分布 -->
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>
                <div class="chart-header">
                  <span>账单状态分布</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="statusChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="mt-20">
          <!-- 套餐销售排行 -->
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>
                <div class="chart-header">
                  <span>套餐销售排行</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="packageChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>

          <!-- 学校消费排行 -->
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>
                <div class="chart-header">
                  <span>学校消费排行</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="schoolChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
    </div>
  </div>
</template>

<script setup name="BillReport">
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import {getBillStatistics, listBills} from "@/api/platform/bills"
import {StorageSerializers as schoolData} from "@vueuse/core";

const { proxy } = getCurrentInstance()

// 图表引用
const amountChart = ref(null)
const statusChart = ref(null)
const packageChart = ref(null)
const schoolChart = ref(null)
// 添加loading状态
const loading = ref(false)
// 新增的状态和数据
const billListVisible = ref(false)
const billList = ref([])
const listLoading = ref(false)
const total = ref(0)

const currentListType = ref('') // 'total', 'paid', etc.

const listQuery = ref({
  page: 1,
  limit: 10,
  startDate: '',
  endDate: '',
  status: ''
})

// 图表类型
const amountChartType = ref('line')

// 日期范围
const dateRange = ref([])

// 查询参数
const queryParams = ref({
  startDate: '',
  endDate: '',
  status: ''
})

// 汇总数据
const summaryData = ref({
  totalBills: 0,
  totalAmount: 0,
  paidBills: 0,
  paymentRate: 0,
  billTrend: 0,
  amountTrend: 0,
  paidTrend: 0,
  rateTrend: 0
})

// 点击统计卡片显示账单列表
import { useRouter } from 'vue-router'

const router = useRouter()

function showBillList(type) {
  // router.push({
  //   path: '/platform/orders/list',
  //   query: {
  //     type,
  //     startDate: queryParams.value.startDate,
  //     endDate: queryParams.value.endDate,
  //     status: type === 'paid' ? '已支付' : type === 'unpaid' ? '待支付' : ''
  //   }
  // })
}

// 获取账单列表
// 获取账单列表
function fetchBillList() {
  listLoading.value = true
  listBills(listQuery.value)
      .then(response => {
        console.log(response)
        if (response.code === 200) {
          billList.value = response.rows  // 修改这里，从 rows 获取数据
          total.value = response.total
        } else {
          proxy.$modal.msgError(response.msg || "获取账单列表失败")
        }
      })
      .catch(error => {
        console.error("获取账单列表失败:", error)
        proxy.$modal.msgError("获取账单列表失败")
      })
      .finally(() => {
        listLoading.value = false
      })
}

// 分页相关方法
function handleSizeChange(val) {
  listQuery.value.limit = val
  fetchBillList()
}

function handleCurrentChange(val) {
  listQuery.value.page = val
  fetchBillList()
}

// 弹窗关闭处理
function handleDialogClose() {
  billList.value = []
  currentListType.value = ''
}

// 获取状态标签类型
function getStatusTagType(status) {
  const map = {
    '已支付': 'success',
    '待支付': 'warning',
    '已过期': 'danger'
  }
  return map[status] || ''
}

// 查看详情
function handleViewDetail(row) {
  // 这里可以跳转到详情页或显示详情弹窗
  proxy.$modal.msgSuccess(`查看账单详情: ${row.billId}`)
}

// 初始化图表
let amountChartInstance = null
let statusChartInstance = null
let packageChartInstance = null
let schoolChartInstance = null

onMounted(() => {
  // 默认查询最近30天数据
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)

  dateRange.value = [
    proxy.parseTime(startDate, '{y}-{m}-{d}'),
    proxy.parseTime(endDate, '{y}-{m}-{d}')
  ]

  queryParams.value.startDate = dateRange.value[0]
  queryParams.value.endDate = dateRange.value[1]

  getData()
})
// 初始化图表
function initCharts(chartsData) {
  nextTick(() => {
    if (!amountChartInstance && amountChart.value) {
      amountChartInstance = echarts.init(amountChart.value);
    }
    if (!statusChartInstance && statusChart.value) {
      statusChartInstance = echarts.init(statusChart.value)
    }
    if (!packageChartInstance && packageChart.value) {
      packageChartInstance = echarts.init(packageChart.value)
    }
    if (!schoolChartInstance && schoolChart.value) {
      schoolChartInstance = echarts.init(schoolChart.value)
    }

    // 使用真实数据渲染图表
    renderCharts(chartsData);
  });
}

function renderCharts(chartsData) {  // 添加参数
  if (!chartsData) {
    console.error("图表数据为空");
    return;
  }

  // 月度趋势图
  if (amountChartInstance && chartsData.monthlyTrend) {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['金额趋势']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartsData.monthlyTrend.map(item => item.month) || []
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      series: [{
        name: '金额趋势',
        type: amountChartType.value,
        data: chartsData.monthlyTrend.map(item => item.totalAmount) || [],
        smooth: true
      }]
    };
    amountChartInstance.setOption(option);
  }

  // 状态分布图
  if (statusChartInstance && chartsData.statusDistribution) {
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: chartsData.statusDistribution.map(item => item.name)
      },
      series: [{
        name: '账单状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartsData.statusDistribution.map(item => ({
          value: item.value || 0,
          name: item.name || '未知'
        }))
      }]
    };
    statusChartInstance.setOption(option);
  }

// 套餐销售排行
  if (packageChartInstance) {
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: chartsData.packageRanking.map(item => item.name)
      },
      series: [
        {
          name: '套餐销售',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          data: chartsData.packageRanking,
          itemStyle: {
            borderRadius: 5
          },
          color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
        }
      ]
    }
    packageChartInstance.setOption(option)
  }

  // 学校消费排行
  if (schoolChartInstance) {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}<br/>消费金额: {c} 元'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      yAxis: {
        type: 'category',
        data: chartsData.schoolRanking.map(item => item.name)
      },
      series: [
        {
          name: '消费金额',
          type: 'bar',
          data: chartsData.schoolRanking.map(item => item.value),
          itemStyle: {
            color: function(params) {
              const colorList = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
              return colorList[params.dataIndex]
            }
          }
        }
      ]
    }
    schoolChartInstance.setOption(option)
  }
}

// 获取数据
// 在您的Vue组件中，确保正确调用getBillStatistics方法
// 获取数据
function getData() {
  loading.value = true;
  getBillStatistics(queryParams.value)
      .then(response => {
        console.log("API响应数据:", response); // 添加这行
        if (response.code === 200) {
          console.log("汇总数据:", response.data.summary);
          console.log("图表数据:", response.data.charts);
          // 更新汇总数据
          summaryData.value = {
            totalBills: response.data.summary.totalBills,
            totalAmount: response.data.summary.totalAmount,
            paidBills: response.data.summary.paidBills,
            paymentRate: response.data.summary.paymentRate,
            billTrend: response.data.summary.billTrend,
            amountTrend: response.data.summary.amountTrend,
            paidTrend: response.data.summary.paidTrend,
            rateTrend: response.data.summary.rateTrend
          };

          // 初始化图表
          initCharts(response.data.charts);
        } else {
          proxy.$modal.msgError(response.msg || "获取统计数据失败");
        }
      })
      .catch(error => {
        console.error("获取数据失败:", error);
        proxy.$modal.msgError("获取统计数据失败");
      })
      .finally(() => {
        loading.value = false;
      });
}

// 日期范围变化
function handleDateChange() {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startDate = dateRange.value[0]
    queryParams.value.endDate = dateRange.value[1]
  } else {
    queryParams.value.startDate = ''
    queryParams.value.endDate = ''
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value = {
    ...queryParams.value,
    status: queryParams.value.status || undefined // 不传则查询所有状态
  };
  getData()
}

function resetQuery() {
  dateRange.value = []
  queryParams.value = {
    startDate: '',
    endDate: '',
    status: ''
  }
  proxy.resetForm("queryRef")
  handleQuery()
}

// 监听图表类型变化
watch(amountChartType, (newVal) => {
  if (amountChartInstance) {
    const option = amountChartInstance.getOption()
    option.series[0].type = newVal
    amountChartInstance.setOption(option)
  }
})

// 窗口大小变化时重新调整图表大小
window.addEventListener('resize', function() {
  amountChartInstance && amountChartInstance.resize()
  statusChartInstance && statusChartInstance.resize()
  packageChartInstance && packageChartInstance.resize()
  schoolChartInstance && schoolChartInstance.resize()
})

</script>

<style scoped>
  /* 基础样式 */
.report-container {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 面包屑导航 */
.breadcrumb-container {
  margin-bottom: 20px;
  padding: 0 10px;
}

.page-title {
  margin: 10px 0 20px;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

/* 搜索区域 */
.search-card {
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

/* 统计卡片区域 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin: 10px 0;
  color: #303133;
}

.stat-trend {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #909399;
}

.stat-trend i {
  margin-right: 4px;
}

.up {
  color: #f56c6c;
}

.down {
  color: #67c23a;
}

/* 图表区域 */
.chart-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header span {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-container {
  width: 100%;
  height: 350px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .el-col {
    margin-bottom: 20px;
  }

  .chart-container {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .el-col {
    width: 100%;
  }

  .stat-value {
    font-size: 24px;
  }
}
</style>
